package com.zlj.jdbc.utils.operation;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class JdbcOperation<T> {
	private static Connection conn;
	private static PreparedStatement pstm;
	private static ResultSet resultSet;
	
	public JdbcOperation() {
		super();
	}
	
	/**
	 * 设置参数
	 */
	public void initParams(PreparedStatement pstm, Object... params) {
		for (int i = 0; i < params.length; i++) {
			try {
				pstm.setObject(i + 1, params[i]);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/*
	 * 执行增删改操作
	 */
	public int update(String sql, Object... params) throws SQLException {
	    	conn = JdbcUtils03.getInstance().getConnection();
			pstm = conn.prepareStatement(sql);
			initParams(pstm, params);
			int update = pstm.executeUpdate();
			return update;
	}
	
	/**
	 * 执行单笔查询操作
	 * @throws SQLException 
	 */
    public T querySingleResult(String sql, RsHandler<T> rh, Object... params) throws SQLException {
    	    conn = JdbcUtils03.getInstance().getConnection();
        	pstm = conn.prepareStatement(sql);
    		initParams(pstm, params);
    		resultSet = pstm.executeQuery();
    		return rh.handler(resultSet);
    }
    
    /*
     * 查询多笔操作
     */
    public List<T> queryMoreResult(String sql, RsHandler<List<T>> rh, Object... params) throws SQLException {
    	    conn = JdbcUtils03.getInstance().getConnection();
        	pstm = conn.prepareStatement(sql);
    		initParams(pstm, params);
    		resultSet = pstm.executeQuery();
    		return rh.handler(resultSet);
    }
}
